package com.uusee.crawler.pageprocessor.baike.mtime;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.PatternMatcherInput;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

import com.uusee.crawler.framework.Processor;
import com.uusee.crawler.model.CrawlStatusCodes;
import com.uusee.crawler.model.CrawlURI;
import com.uusee.crawler.util.PageProcessorUtils;
import com.uusee.shipshape.bk.Constants;
import com.uusee.shipshape.bk.model.Baike;
import com.uusee.shipshape.bk.model.BaikeImage;
import com.uusee.shipshape.bk.model.Episode;
import com.uusee.shipshape.gt.util.RenameUtils;
import com.uusee.util.StringUtils;

public class EpisodePageProcessor extends Processor {
	private static final String BEFORE_FILTER_REG = ".*?<select id=\"cbSection\" onchange=\"location = this.value;\">.*?</select>";
	private static final String AFTER_FILTER_REG = "<div class=\"ele_outer\">\\s*?<div class=\"ele_inner pl12 pr12 pb30 mt5\">\\s*?<h2>分集查看剧情</h2>.*";
	private static final String AFTER_FILTER_REG_2 = "<div id=\"PageNavigator\" class='pagenav tc mt30'>.*";
	private static final String MODEL_REG = "</a>(.*?)<a name=\"episode_[0-9]+\".*?>";
	
	private static final String NAME1_REG = "<p class=\"mt30\">.*?<em class=\"ml15 mr15 bold\">(.*?)</em>";
	private static final String NAME2_REG = "<p class=\"mt30\">([^<]*?)<em.*?>";
	private static final String VOLUMN_SEASON_STRING_REG = "<p class=\"mt30\">(.*?)<em.*?>";
	private static final String VOLUMN_REG = "<p class=\"mt30\">.*?第\\s*([0-9]+)\\s*集.*?<em.*?>";
	private static final String SEASON_REG = "<p class=\"mt30\">.*?第\\s*[0-9]+\\s*集 \\(第\\s*?([一|二|三|四|五|六|七|八|九|十|百]+).*?<em.*?>";
	private static final String SUMMARY_REG = "<div class=\"line_dot mt12\"></div>(.*)";
	
	
	protected void innerProcess(CrawlURI crawlURI) {
		if (!canProcess(crawlURI)) {
			return;
		}

		try {
			Date crawlDate = new Date();
			String crawlUser = "uusee-crawler";
			String crawlUrl = crawlURI.getCrawlUrl();
			String oriId = PageProcessorUtils.getValue("http://www.mtime.com/movie/([0-9]+)/", crawlUrl);
			String sourceSite = crawlURI.getSourceSite();
			String crawlResult = crawlURI.getCrawlResult();
			List<CrawlURI> episodeCrawlURIList = (List<CrawlURI>)crawlURI.getModel();
			
			crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_SUCCESS);
			
			String text = StringUtils.replace(crawlResult, BEFORE_FILTER_REG, "");
			text = StringUtils.replace(text, AFTER_FILTER_REG, "");
			text = StringUtils.replace(text, AFTER_FILTER_REG_2, "");
			text = text.replaceAll("&nbsp[;]?", "");
			text = text+"<a name=\"episode_0000\"></a>";
			
			
			PatternCompiler compiler = new Perl5Compiler();
			Pattern pattern = compiler.compile(MODEL_REG, Perl5Compiler.CASE_INSENSITIVE_MASK);
			PatternMatcher matcher = new Perl5Matcher();
			PatternMatcherInput input = new PatternMatcherInput(text);
			while (matcher.contains(input, pattern)) {
				MatchResult m = matcher.getMatch();
				String modelText = m.group(1);
				
				modelText = modelText.replaceAll("(<span.*?>)|(</span>)", "");
				modelText = modelText.replaceAll("(<a.*?>)|(</a>)", "");
				
				String name1 = PageProcessorUtils.getValue(NAME1_REG, modelText);
				String name2 = PageProcessorUtils.getValue(NAME2_REG, modelText);
				
				String svolumnSeason = PageProcessorUtils.getValue(VOLUMN_SEASON_STRING_REG, modelText);
				int volumn = Integer.valueOf(PageProcessorUtils.getValue(VOLUMN_REG, modelText));
				String sSeason = PageProcessorUtils.getValue(SEASON_REG, modelText);
				int season = 0;
				if (StringUtils.isNotEmpty(sSeason)) {
					try{
						season = RenameUtils.chNumToNum(sSeason);
					}catch(Exception e){
						season = 0;					}
				} 
				if (season==0) {
					season = RenameUtils.getSeason(svolumnSeason);
				}
				
				
				String summary = PageProcessorUtils.getValue(SUMMARY_REG, modelText);
				summary = summary.toLowerCase().replaceAll("<p.*?>", "<p>");
				summary = summary.toLowerCase().replaceAll("<\\s*p\\s*>", "START_P");
				summary = summary.replaceAll("<\\s*/p\\s*>", "END_P");
				summary = summary.replaceAll("<[^<]*?>", "");
				summary = summary.replaceAll("START_P", "<p>");
				summary = summary.replaceAll("END_P","</p>");
				
				if (volumn==0 || StringUtils.isEmpty(name2)) {
					continue;
				}
				
				Episode episode = new Episode();
				Baike baike = new Baike();
				baike.setSourceSite(sourceSite);
				baike.setOriId(oriId);
				episode.setBaike(baike);
				if (StringUtils.isNotEmpty(name1)) {
					episode.setName(name1);
				} else {
					if (season!=0) {
						episode.setName("第"+season+"季-第"+volumn+"集");
					}else{
						episode.setName("第"+volumn+"集");
					}
				}
				episode.setName2(name2.trim());
				episode.setSeason(season);
				episode.setVolumn(volumn);
				episode.setSummary(summary);
				episode.setUpdateUser(crawlUser);
				episode.setUpdateDate(crawlDate);
				
				CrawlURI episodeCrawlURI = new CrawlURI();
				episodeCrawlURI.setCrawlUrl(crawlUrl);
				episodeCrawlURI.setSourceSite(crawlURI.getSourceSite());
				episodeCrawlURI.setModel(episode);
				episodeCrawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_SUCCESS);
				
				episodeCrawlURIList.add(episodeCrawlURI);
			}
		} catch ( Exception e ) {
			e.printStackTrace();
			crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_EXCEPTION);
		}
	}
	
	private boolean canProcess(CrawlURI crawlURI) {
		int crawlStatus = crawlURI.getCrawlStatus();
		if (crawlStatus == CrawlStatusCodes.FETCH_SUCCESS) {
			return true;
		} else if (crawlStatus == CrawlStatusCodes.FETCH_SC_NOT_OK) {
			crawlURI.setCrawlStatus(CrawlStatusCodes.PAGE_PROCESS_INVALID);
			return false;
		} else {
			return false;
		}
	}
}
